package com.yuke.cloud.service.wmc.controller.frontend;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.yuke.cloud.common.base.constant.MQConstants;
import com.yuke.cloud.common.base.dto.LoginAuthDto;
import com.yuke.cloud.common.core.mq.RabbitMetaMessage;
import com.yuke.cloud.common.core.mq.RabbitSender;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoDto;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.uac.dto.UserInfoDto;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.wmc.entity.WmsGoodsTransfer;
import com.yuke.cloud.service.wmc.entity.WmsStockOut;
import com.yuke.cloud.service.wmc.entity.WmsStorage;
import com.yuke.cloud.service.wmc.entity.WmsWarehouse;
import com.yuke.cloud.service.wmc.service.WmsGoodsTransferService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.service.wmc.service.WmsStockOutService;
import com.yuke.cloud.service.wmc.service.WmsStorageService;
import com.yuke.cloud.service.wmc.service.WmsWarehouseService;
import com.yuke.cloud.service.wmc.util.DistancdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import com.yuke.cloud.common.core.support.BaseController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by zys on 2019/01/10.
 */
@Api(value = "WEB - WmsGoodsTransferController", tags = "处理WmsGoodsTransfer相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/wms/goods_transfer")
public class WmsGoodsTransferController extends BaseController {
    @Resource
    private WmsGoodsTransferService wmsGoodsTransferService;
    @Resource
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private PmcFeignApi pmcFeignApi;
    @Autowired
    private UacUserFeignApi uacUserFeignApi;
    @Autowired
    private RabbitSender rabbitSender;

    @Resource
    private WmsStockOutService wmsStockOutService;
    @Resource
    private WmsStorageService wmsStorageService;

    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "wmsGoodsTransfer", value = "该数据记录的POJO") @RequestBody WmsGoodsTransfer wmsGoodsTransfer) {
        Long aLong = wmsGoodsTransferService.generateIdit();
        wmsGoodsTransfer.setTransferId(aLong);
        wmsGoodsTransferService.save(wmsGoodsTransfer);
        Map map = new HashMap();
        map.put("MessageType", "newTransferApplication");
        map.put("warehouseId", wmsGoodsTransfer.getBeTransferedWarehouseId().toString());
        map.put("body", "查找仓库管理员");
        RabbitMetaMessage rabbitMetaMessage = new RabbitMetaMessage();
        rabbitMetaMessage.setExchange(MQConstants.BUSINESS_EXCHANGE);
        rabbitMetaMessage.setRoutingKey(MQConstants.BUSINESS_KEY_TMC);
        rabbitMetaMessage.setPayload(JSON.toJSONString(map));
        try {
            rabbitSender.send(rabbitMetaMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return WrapMapper.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        wmsGoodsTransferService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "wmsGoodsTransfer", value = "需要修改的内容") @RequestBody WmsGoodsTransfer wmsGoodsTransfer) {
        //add by wg 20190502 如果状态是已确认发货，则对被调货方进行出库记录处理,同时减少库存量
        if (wmsGoodsTransfer.getTransferStatus() == 4) {
            WmsWarehouse wmsWarehouse = new WmsWarehouse();
            wmsWarehouse.setWarehouseId(wmsGoodsTransfer.getBeTransferedWarehouseId());
            wmsWarehouse.setGroupId(wmsGoodsTransfer.getTransferSpecId());//存储specid
            wmsWarehouse.setArea(-wmsGoodsTransfer.getTransferNum());//存储调货数量
//            wmsWarehouseService.updatestorage(wmsWarehouse);
            wmsStorageService.updateWarehouseStorage(wmsGoodsTransfer.getBeTransferedWarehouseId(), wmsGoodsTransfer.getTransferSpecId(), -wmsGoodsTransfer.getTransferNum(), 0);

            Example exampleStorage = new Example(WmsStorage.class);
            Example.Criteria criteriaStorage = exampleStorage.createCriteria();
            criteriaStorage.andEqualTo("warehouseId", wmsGoodsTransfer.getBeTransferedWarehouseId());
            criteriaStorage.andEqualTo("specId", wmsGoodsTransfer.getTransferSpecId());
            List<WmsStorage> listWmsStorage = wmsStorageService.selectByExample(exampleStorage);
            if (listWmsStorage == null || listWmsStorage.size() <= 0) {
                return WrapMapper.error();
            }
            Long productId = listWmsStorage.get(0).getProductId();

            WmsStockOut wmsStockOut = new WmsStockOut();
            wmsStockOut.setStockOutId(super.generateId());
            wmsStockOut.setWarehouseId(wmsGoodsTransfer.getBeTransferedWarehouseId());
            wmsStockOut.setOutType((byte)1);
            wmsStockOut.setSpecId(wmsGoodsTransfer.getTransferSpecId());
            wmsStockOut.setProductId(productId);
            wmsStockOut.setOutNumber(wmsGoodsTransfer.getTransferNum());
            wmsStockOut.setTransOrderId(wmsGoodsTransfer.getTransferId());
            LoginAuthDto loginAuthDto = super.getLoginAuthDto();
            wmsStockOut.setUpdateId(loginAuthDto.getUserId());
            Date date = new Date();
            wmsStockOut.setOutboundTime(date);
            wmsStockOut.setUpdateTime(date);
            wmsStockOutService.save(wmsStockOut);
        }

        // todo 对于同意调货，被调货的仓库库存需要锁定，暂时没有做
        wmsGoodsTransferService.update(wmsGoodsTransfer);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<WmsGoodsTransfer> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        WmsGoodsTransfer wmsGoodsTransfer = wmsGoodsTransferService.findById(id);
        return WrapMapper.ok(wmsGoodsTransfer);
    }

    @GetMapping("/getWarehouseSpec")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<PageInfo> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(required = false) Integer page,
                                  @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(required = false) Integer size,
                                  @ApiParam(name = "warehouseId", value = "仓库ID") @RequestParam("warehouseId") Long warehouseId,
                                  @ApiParam(name = "specId", value = "商品ID") @RequestParam("specId") Long specId,
                                  @ApiParam(name = "specName", value = "商品名称") @RequestParam("specName") String specName
    ) {
        PageHelper.startPage(page, size);
        List<Map> list = wmsGoodsTransferService.findtransferspec(specId, warehouseId);
        PageInfo pageInfo = new PageInfo(list);
        WmsWarehouse byId = wmsWarehouseService.findById(warehouseId);
        if (list.size() == 0) {
            // mod by wg 20190502 对没有的数据进行处理
//            return null;
            pageInfo.setList(list);
            return WrapMapper.ok(pageInfo);
        }
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put("specName", specName);
            double longitude = Double.parseDouble(list.get(i).get("longitude").toString());
            double latitude = Double.parseDouble(list.get(i).get("latitude").toString());
            double distance = DistancdUtil.Distance(byId.getLongitude().doubleValue(), byId.getLatitude().doubleValue(), longitude, latitude);
            list.get(i).put("distance", distance);
        }
        Collections.sort(list, (o1, o2) -> {
            int distance1 = (int) Double.parseDouble(o1.get("distance").toString());
            int distance2 = (int) Double.parseDouble(o2.get("distance").toString());
            return Integer.compare(distance1, distance2);
        });

        pageInfo.setList(list);
        return WrapMapper.ok(pageInfo);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<WmsGoodsTransfer>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                    @RequestParam(required = false) Integer transferStatus,
                                                    @RequestParam(required = false) Long transferWarehouseId,
                                                    @RequestParam(required = false) Long beTransferedWarehouseId,
                                                    @RequestParam(required = false) Long transferId,
                                                    @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") Date beginTime,
                                                    @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") Date endTime,
                                                    @RequestParam(required = false) Integer returnStatus)

    {
        PageHelper.startPage(page, size);
        Example example = new Example(WmsGoodsTransfer.class);
        example.setOrderByClause("application_date desc");
        Example.Criteria criteria = example.createCriteria();
        if (!ifnull(transferStatus)) {
            criteria.andEqualTo("transferStatus", transferStatus);
        }
        if (!ifnull(transferWarehouseId)) {
            criteria.andEqualTo("transferWarehouseId", (byte) transferWarehouseId.intValue());
        }
        if (!ifnull(beTransferedWarehouseId)) {
            criteria.andEqualTo("beTransferedWarehouseId", beTransferedWarehouseId);
        }
        if (!ifnull(beginTime)) {
            criteria.andGreaterThanOrEqualTo("applicationDate", beginTime);
        }
        if (!ifnull(endTime)) {
            criteria.andLessThanOrEqualTo("applicationDate", endTime);
        }

        if (!ifnull(returnStatus)) {
            criteria.andEqualTo("returnStatus", (byte) returnStatus.intValue());
        }

        if (!ifnull(transferId)) {
            criteria.andEqualTo("transferId", transferId);
        }

        List<WmsGoodsTransfer> wmsGoodsTransfers = wmsGoodsTransferService.selectByExample(example);
        if (wmsGoodsTransfers == null || wmsGoodsTransfers.size() == 0) {
            List<WmsGoodsTransfer> list = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(list);
            return WrapMapper.ok(pageInfo);
        }
        List<Long> warehouseId = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < wmsGoodsTransfers.size(); i++) {
            WmsGoodsTransfer wmsGoodsTransfer = wmsGoodsTransfers.get(i);
            warehouseId.add(wmsGoodsTransfer.getTransferWarehouseId());
            warehouseId.add(wmsGoodsTransfer.getBeTransferedWarehouseId());
            list.add(wmsGoodsTransfer.getDealPeople());
            if (i == wmsGoodsTransfers.size() - 1) {
                sb.append(wmsGoodsTransfer.getTransferSpecId());
            } else {
                sb.append(wmsGoodsTransfer.getTransferSpecId()).append(",");
            }
        }
        Example example1 = new Example(WmsWarehouse.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andIn("warehouseId", warehouseId);
        List<WmsWarehouse> wmsWarehouses = wmsWarehouseService.selectByExample(example1);
        List<ProdSpecInfoDto> specInfoDtosBySpecIds = pmcFeignApi.getSpecInfoDtosBySpecIds(sb.toString());
        Wrapper<List<UserInfoDto>> userInfoByUserIds = uacUserFeignApi.getUserInfoByUserIds(list);
        if (userInfoByUserIds == null || userInfoByUserIds.getResult() == null || userInfoByUserIds.getResult().size() == 0) {
            List<WmsGoodsTransfer> list2 = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(list2);
            return WrapMapper.ok(pageInfo);
        }
        if (specInfoDtosBySpecIds == null || specInfoDtosBySpecIds.size() == 0) {
            List<WmsGoodsTransfer> list3 = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(list3);
            return WrapMapper.ok(pageInfo);
        }
        List<UserInfoDto> result = userInfoByUserIds.getResult();
        for (int i = 0; i < wmsGoodsTransfers.size(); i++) {
            for (int j = 0; j < wmsWarehouses.size(); j++) {
                if (wmsGoodsTransfers.get(i).getTransferWarehouseId().toString().equals(wmsWarehouses.get(j).getWarehouseId().toString())) {
                    wmsGoodsTransfers.get(i).setWarehouseName(wmsWarehouses.get(j).getWarehouseName());
                }
                if (wmsGoodsTransfers.get(i).getBeTransferedWarehouseId().toString().equals(wmsWarehouses.get(j).getWarehouseId().toString())) {
                    wmsGoodsTransfers.get(i).setBeWarehouseName(wmsWarehouses.get(j).getWarehouseName());
                }
                for (int k = 0; k < specInfoDtosBySpecIds.size(); k++) {
                    if (wmsGoodsTransfers.get(i).getTransferSpecId().toString().equals(specInfoDtosBySpecIds.get(k).getSpecId().toString())) {
                        wmsGoodsTransfers.get(i).setSpecName(specInfoDtosBySpecIds.get(k).getSpecName());
                    }
                }
            }
            for (int k = 0; k < result.size(); k++) {
                if (wmsGoodsTransfers.get(i).getDealPeople().toString().equals(result.get(k).getUserId().toString())) {
                    wmsGoodsTransfers.get(i).setDealPeopleName(result.get(k).getUserName());
                }
            }
        }
        PageInfo pageInfo = new PageInfo(wmsGoodsTransfers);
        return WrapMapper.ok(pageInfo);
    }

    private boolean ifnull(Object object) {
        if (object == null || object.toString().equals("") || object.toString().equals("undefined")) {
            return true;
        } else {
            return false;
        }

    }
}
